const calcAccuracySummary = (tempAccuracyData, config = {}) => {
  // 验证输入数据的合法性
  if (!Array.isArray(tempAccuracyData)) {
    throw new Error('输入数据不是数组');
  }
  tempAccuracyData.forEach((item, index) => {
    if (item !== 0 && item !== 1) {
      throw new Error(`第 ${index + 1} 个数据项无效，必须是 0 或 1，实际值为: ${item}`);
    }
  });

  // 配置项，提供更灵活的选项来调整统计逻辑
  const {
    trackConsecutiveSegments = true, // 是否统计连续段
    trackTrend = false, // 是否分析趋势（连错次数超过某个阈值时触发）
    maxTrendErrorCount = 3, // 触发趋势分析的最大连续错误次数
    calculateErrorRate = true, // 是否计算错误率（即每个错误的比例）
    errorRateThreshold = 0.1, // 错误率阈值，用于标记为高误差模式
  } = config;

  // 初始化统计变量
  let correctCount = 0; // 正确次数
  let incorrectCount = 0; // 错误次数
  let maxConsecutiveCorrect = 0; // 最大连续正确次数
  let maxConsecutiveIncorrect = 0; // 最大连续错误次数
  let currentConsecutiveCorrect = 0; // 当前连续正确次数
  let currentConsecutiveIncorrect = 0; // 当前连续错误次数
  let totalConsecutiveCorrect = 0; // 总连续正确次数
  let totalConsecutiveIncorrect = 0; // 总连续错误次数
  let consecutiveCorrectSegments = 0; // 连续正确段数
  let consecutiveIncorrectSegments = 0; // 连续错误段数

  // 额外统计参数：错误分类（系统性错误与偶然错误）
  let systemErrorCount = 0; // 系统性错误次数
  let randomErrorCount = 0; // 偶然错误次数
  let totalErrors = 0; // 错误总数

  // 趋势分析：如果连续错误超过一定次数，标记为趋势
  let isTrendDetected = false;

  // 高误差模式分析（根据错误率）
  let isHighErrorMode = false;

  // 遍历每个结果，计算准确率和其他统计信息
  tempAccuracyData.forEach((result, index) => {
    if (result === 1) {
      correctCount++;
      if (currentConsecutiveIncorrect > 0) {
        // 更新最大连续错误次数
        maxConsecutiveIncorrect = Math.max(maxConsecutiveIncorrect, currentConsecutiveIncorrect);
        totalConsecutiveIncorrect += currentConsecutiveIncorrect;
        if (trackConsecutiveSegments) consecutiveIncorrectSegments++;
        currentConsecutiveIncorrect = 0;
      }
      currentConsecutiveCorrect++;
    } else {
      incorrectCount++;
      totalErrors++;

      if (currentConsecutiveCorrect > 0) {
        // 更新最大连续正确次数
        maxConsecutiveCorrect = Math.max(maxConsecutiveCorrect, currentConsecutiveCorrect);
        totalConsecutiveCorrect += currentConsecutiveCorrect;
        if (trackConsecutiveSegments) consecutiveCorrectSegments++;
        currentConsecutiveCorrect = 0;
      }
      currentConsecutiveIncorrect++;

      // 错误分类：当连续错误次数小于 maxTrendErrorCount 时，视为偶然错误
      if (currentConsecutiveIncorrect <= maxTrendErrorCount) {
        randomErrorCount++;
      } else {
        systemErrorCount++;
      }

      // 趋势检测：如果连续错误超过阈值，标记为趋势
      if (trackTrend && currentConsecutiveIncorrect > maxTrendErrorCount && !isTrendDetected) {
        isTrendDetected = true;
      }
    }
  });

  // 检查最后的连续段
  if (currentConsecutiveCorrect > 0) {
    maxConsecutiveCorrect = Math.max(maxConsecutiveCorrect, currentConsecutiveCorrect);
    totalConsecutiveCorrect += currentConsecutiveCorrect;
    if (trackConsecutiveSegments) consecutiveCorrectSegments++;
  }
  if (currentConsecutiveIncorrect > 0) {
    maxConsecutiveIncorrect = Math.max(maxConsecutiveIncorrect, currentConsecutiveIncorrect);
    totalConsecutiveIncorrect += currentConsecutiveIncorrect;
    if (trackConsecutiveSegments) consecutiveIncorrectSegments++;
  }

  // 计算平均连续正确和错误次数
  const avgConsecutiveCorrect =
    consecutiveCorrectSegments > 0 ? totalConsecutiveCorrect / consecutiveCorrectSegments : 0;
  const avgConsecutiveIncorrect =
    consecutiveIncorrectSegments > 0 ? totalConsecutiveIncorrect / consecutiveIncorrectSegments : 0;

  // 计算准确率
  const accuracyRate = correctCount + incorrectCount > 0 ? correctCount / (correctCount + incorrectCount) : 0;

  // 错误率分析：是否误差超过阈值
  if (calculateErrorRate && totalErrors > 0) {
    const errorRate = incorrectCount / totalErrors;
    isHighErrorMode = errorRate > errorRateThreshold;
  }

  // 返回计算结果
  return {
    count: correctCount + incorrectCount,
    correctCount,
    incorrectCount,
    accuracyRate,
    maxConsecutiveCorrect,
    maxConsecutiveIncorrect,
    consecutiveCorrectSegments,
    consecutiveIncorrectSegments,
    avgConsecutiveCorrect,
    avgConsecutiveIncorrect,
    currentConsecutiveCorrect,
    currentConsecutiveIncorrect,
    systemErrorCount,
    randomErrorCount,
    isTrendDetected, // 是否检测到趋势
    isHighErrorMode, // 是否为高误差模式
  };
};

// 中文映射，用于展示结果时的说明
const ACCURACY_SUMMARY_CN_MAP = {
  count: '统计次数',
  correctCount: '正确次数',
  incorrectCount: '错误次数',
  accuracyRate: '准确率',
  maxConsecutiveCorrect: '最大连续正确次数',
  maxConsecutiveIncorrect: '最大连续错误次数',
  consecutiveCorrectSegments: '连续正确段数',
  consecutiveIncorrectSegments: '连续错误段数',
  avgConsecutiveCorrect: '平均连续正确次数',
  avgConsecutiveIncorrect: '平均连续错误次数',
  currentConsecutiveCorrect: '当前连续正确次数',
  currentConsecutiveIncorrect: '当前连续错误次数',
  systemErrorCount: '系统性错误次数',
  randomErrorCount: '偶然错误次数',
  isTrendDetected: '是否检测到趋势',
  isHighErrorMode: '是否为高误差模式',
};

module.exports = {
  calcAccuracySummary,
  ACCURACY_SUMMARY_CN_MAP,
};
